package view;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.DownloadProgress;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

/**
 *
 */
public class DownloadView extends JFrame implements Observer {
    private ArrayList<JProgressBar> progressBars;

    public DownloadView(ArrayList<String> files) {
        this.progressBars = new ArrayList<JProgressBar>();
        
        BoxLayout layout = new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS);
        this.setLayout(layout);
        
        for(String url : files) {
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            
            JProgressBar bar = new JProgressBar();
            bar.setName(url);
            this.progressBars.add(bar);
            
            panel.add(new JLabel(url));
            panel.add(bar);
            panel.add(Box.createRigidArea(new Dimension(1, 10)));
            
            this.add(panel);
        }
        
        JButton close = new JButton("Schliessen");
        close.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                SwingUtilities.getWindowAncestor((JButton )e.getSource()).dispose();
            }
        });
        
        this.add(close);
        this.add(Box.createRigidArea(new Dimension(1, 10)));
        
        this.setTitle("Downloads");
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }

    
    public void update(Observable o, Object arg) {
        DownloadProgress progress = (DownloadProgress) arg;
        
        for(JProgressBar bar : this.progressBars){
            if(bar.getName().equals(progress.getUrl())) {
                bar.setValue(progress.getProgressValue());
            }
           
        }
        
        this.repaint();
    }
    
}
